package com.nurese.controller;

import com.nurese.entity.User;
import com.nurese.entity.User;
import com.nurese.service.UserService;
import com.nurese.utils.MapControll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    private final String LIST="User/list";
    private final String ADD="User/add";
    private final String UPDATE="User/update";



    @Autowired
    private UserService userService;

    @GetMapping("/add")
    public String create(){
        return ADD;
    }

    @PostMapping("/create")
    @ResponseBody
//    public void  create(User user){
//        userService.create(user);
//    }
    public Map<String,Object> create(User user){
//        userService.create(user);
        int result= userService.create(user);
        if (result<=0){
//            新增失败
            return MapControll.getInstance().error().getMap();

        }
        return MapControll.getInstance().success().getMap();
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String,Object> delete(@PathVariable("id") Integer id){
        int result = userService.delete(id);
        if(result<=0){
            return MapControll.getInstance().error().getMap();
        }
        return MapControll.getInstance().success().getMap();
    }
    @PostMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String ids){
        int result = userService.delete(ids);
        if(result<=0){
            return MapControll.getInstance().error().getMap();
        }
        return MapControll.getInstance().success().getMap();
    }


    @PostMapping("/update")
    @ResponseBody
//    @RequestBody
    public Map<String,Object> update(User user){
        System.out.println("======22"+user);
        int result = userService.update(user);
        if(result<=0){
            return MapControll.getInstance().error().getMap();
        }
        return MapControll.getInstance().success().getMap();
    }


    @GetMapping ("/detail/{id}")
    public String detail(@PathVariable("id") Integer id,ModelMap modelMap){

        User user=userService.detail(id);
        modelMap.addAttribute("user",user);
       return UPDATE;
    }


    @PostMapping("/query")
    @ResponseBody
    public Map<String,Object> query(User user){
        List<User> list =userService.query(user);
        Integer count=userService.count(user);
        return MapControll.getInstance().success().put("data",list).put("count",count).getMap();
    }

    @GetMapping("/list")
    public String list(){

        return LIST;
    }
}

